package com.boot.down.service.impl;

import com.boot.down.entity.RedPaper;
import com.boot.down.mapper.RedPaperMapper;
import com.boot.down.service.RedPaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 红包实现类
 */
@Service
public class RedPaperServiceImpl implements RedPaperService {

    @Autowired
    private RedPaperMapper redPaperMapper = null;

    @Autowired
    private RedisTemplate redisTemplate = null;


    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public RedPaper getRedPaper(Long id) {

        return redPaperMapper.getRedPaper(id);
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int decreaseRedPaper(Long id) {

        return redPaperMapper.decreaseRedPaper(id);
    }

    @Override
    public int initRedPaper(Integer smallSupCount, BigDecimal smallPrice) {

        RedPaper redPaper = new RedPaper();
        redPaper.setCreateTime(new Date());
        redPaper.setPrice(smallPrice.multiply(BigDecimal.valueOf(smallSupCount)));
        redPaper.setRemark("这个红包个数为" + smallSupCount + "抓紧抢");
        redPaper.setSmallCount(smallSupCount); //默认为总数
        redPaper.setSmallPrice(smallPrice);
        redPaper.setUserId(3); //默认用户3
        redPaper.setVersion(0);
        redPaper.setSmallSupCount(smallSupCount); //剩余个数

        int result = redPaperMapper.insertRedPaper(redPaper);
        if(result > 0){
            //初始化redis的红包信息
            Jedis jedis =  (Jedis) redisTemplate.getConnectionFactory().getConnection().getNativeConnection();
            //红包个数
            jedis.hset("red_paper_"+redPaper.getId(), "smallSupCount", String.valueOf(smallSupCount));
            //每个红包的金额
            jedis.hset("red_paper_"+redPaper.getId(), "smallPrice", String.valueOf(smallPrice));
            return result;
        }
        return 0;
    }
}
